<?php
namespace App\Controller;
use Common\Controller\AppbaseController;
use Common\Controller\AppmemberbaseController;
use Common\Controller\AppuserbaseController;
use Common\Service\WxpayService;
use Think\Exception;

class UserController extends AppmemberbaseController {

    /**
     * 根据商户id添加通话记录
     */
    public function call(){
        $business_id=I('id',0,'intval');
        if(!$business_id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_normal_business_by_id($business_id);
        if($business!==false){
            $data['business_id']=$business_id;
            $data['business_name']=$business['name'];
            $data['create_time']=time();
            $data['user_id']=$this->userId;
            $result=M('PhoneRecord')->add($data);
            if($result!==false){
                $this->jsonReturn(1,'记录成功');
            }else{
                $this->jsonReturn(0,'记录失败');
            }
        }else{
            $this->jsonReturn(0,'商户不存在或已被删除');
        }
    }

    /**
     * 获取全部通话记录
     */
    public function getPhoneRecords(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $phoneRecords=M('PhoneRecord')->where(['user_id'=>$this->userId,'is_deleted'=>0])->order('create_time DESC')->limit($start,$this->pageLimit+1)->field('create_time,business_name,business_id,id')->select();
        if($phoneRecords){
            $phoneRecords=$this->checkEndPage($phoneRecords);
            $this->jsonReturn(1,'获取成功',$phoneRecords);
        }else{
            $this->jsonReturn(1,'没有更多通话记录了',(object)[]);
        }
    }

    /**
     * 删除通话记录
     */
    public function deletePhoneRecords(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $phoneRecord=M('PhoneRecord')->where(['user_id'=>$this->userId,'id'=>$id])->find();
        if($phoneRecord){
            $result=M('PhoneRecord')->where(['id'=>$id])->save(['is_deleted'=>1]);
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'记录不存在');
        }
    }

    /**
     *  意见反馈
     */
    public function advice(){
        $content=I('content');
        if(!$content){
            $this->jsonReturn(0,'内容必填');
        }
        $data['content']=$content;
        $data['user_id']=$this->userId;
        $data['create_time']=time();
        $result=M('Advice')->add($data);
        if($result!==false){
            $this->jsonReturn(1,'添加成功');
        }else{
            $this->jsonReturn(0,'建议添加失败');
        }
    }

    /**
     *  退出登录
     */
    public function logout(){
        $result=M('User')->where(['id'=>$this->userId])->save(['token'=>'']);
        if($result!==false){
            $this->jsonReturn(1,'退出成功');
        }else{
            $this->jsonReturn(0,'退出失败');
        }
    }

    /**
     *  添加用户证书到期提醒
     */
    public function addUserCert(){
        $name=I('name');
        $end_time=I('time',0,'intval');
        if(!$name){
            $this->jsonReturn(0,'名称必填');
        }
        if(!$end_time||strlen($end_time)!=10){
            $this->jsonReturn(0,'时间不正确');
        }
        $data['name']=$name;
        $data['end_time']=$end_time;
        $data['create_time']=time();
        $data['user_id']=$this->userId;
        $result=M('UserCert')->add($data);
        if($result!==false){
            $this->jsonReturn(1,'添加成功');
        }else{
            $this->jsonReturn(0,'添加失败');
        }
    }

    /**
     *  删除用户证书到期提醒
     */
    public function deleteUserCert(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $userCert=M('UserCert')->where(['user_id'=>$this->userId,'id'=>$id])->find();
        if($userCert){
            $result=M('UserCert')->where(['id'=>$id])->delete();
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'记录不存在');
        }
    }

    /**
     *  获取用户全部证书到期提醒
     */
    public function getUserCerts(){
        $userCert=M('UserCert')->where(['user_id'=>$this->userId])->field('id,name,end_time as time,is_expired')->select();
        if($userCert){
                $this->jsonReturn(1,'获取成功',$userCert);
        }else{
            $this->jsonReturn(1,'还没有证件',[]);
        }
    }

    /**
     * 获取个人信息
     */
    public function getUserInfo(){
        $pre=$this->uploadPre;
        $avatar=empty($this->user['avatar'])?"":$pre.$this->user['avatar'];
        $company=M('InsuranceCompany')->where(['id'=>$this->user['insurance_company_id']])->find();
        $company=empty($company)?'':$company['name'];
        $userInfo=['avatar'=>$avatar,'username'=>$this->user['username'],'car_type'=>$this->user['car_type'],'car_license'=>$this->user['car_license'],'insurance_company'=>$company,'insurance_company_id'=>$this->user['insurance_company_id'],'phone'=>$this->user['phone']];
        $this->jsonUnslashesReturn(1,'获取成功',$userInfo);
    }

    /**
     * 设置个人信息
     */
    public function setUserInfo(){
        $avatar=I('avatar');
        $avatar=$this->getSaveImageUrl($avatar);
        $username=I('username');
        $car_type=I('car_type');
        $car_license=I('car_license');
        $insurance_company_id=I('insurance_company_id',0,'intval');
        if(!$username){
            $this->jsonReturn(0,'缺少用户名');
        }
        if($insurance_company_id!=0){
            $company=M('InsuranceCompany')->where(['id'=>$insurance_company_id])->find();
            if(!$company){
                $this->jsonReturn(0,'保险公司不存在');
            }
        }
        $data['username']=$username;
        $data['avatar']=$avatar;
        $data['car_type']=$car_type;
        $data['car_license']=$car_license;
        $data['insurance_company_id']=$insurance_company_id;
        $result=M('User')->where(['id'=>$this->userId])->save($data);
        if($result!==false){
            $this->jsonReturn(1,'修改成功');
        }else{
            $this->jsonReturn(0,'修改失败');
        }
    }

    /**
     * 用户上传接口
     */
    public function userUploadImage(){
        $result=$this->uploadFile('user');
        if($result['status']!=='error'){
            $fileName=$result['info']['file']['savepath'].$result['info']['file']['savename'];
            $this->jsonUnslashesReturn(1,'上传成功',$this->uploadPre.$fileName);
        }else{
            $this->jsonReturn(0,$result['message']);
        }
    }

    /**
     * 获取全部保险公司
     */
    public function getInsuranceCompanies(){
        $companies=M('InsuranceCompany')->select();
        if($companies){
            $this->jsonReturn(1,'获取成功',$companies);
        }else{
            $this->jsonReturn(1,'还没有添加保险公司',[]);
        }
    }

    /**
     * 更改密码
     */
    public function changePassword(){
        $oldPass=I('oldPass');
        $newPass=I('newPass');
        if(!$oldPass||!$newPass){
            $this->jsonReturn(0,'新旧密码必填');
        }
        if(!$this->checkPassword($oldPass)||!$this->checkPassword($newPass)){
            $this->jsonReturn(0,'密码必须是6到25位的数字字母下划线');
        }
        if(empty($this->user['password'])){
            $this->jsonReturn(0,'您是第三方用户，请直接通过忘记密码来设置密码');
        }
        if (sp_compare_password($oldPass, $this->user['password'])) {
            $data['password'] = sp_password($newPass);
            $data['id'] = $this->userId;
            $result = M('User')->save($data);
            if ($result !== false) {
                $this->jsonReturn(1,'修改成功');
            } else {
                $this->jsonReturn(0,'修改失败');
            }
        } else {
            $this->jsonReturn(0,'原始密码不正确');
        }
    }

    //检测密码
    private function checkPassword($password){
        if(preg_match("/^\w{6,25}$/",$password)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更换手机号
     */
    public function changePhone(){
        $oldPhone=$this->user['phone'];
        $oldPhoneSms=I('oldPhoneSms');
        $newPhone=I('newPhone');
        $newPhoneSms=I('newPhoneSms');
        if(!$newPhone){
            $this->jsonReturn(0,'电话必填');
        }
        if(!$oldPhoneSms||!$newPhoneSms){
            $this->jsonReturn(0,'验证码必填');
        }
        if(!lt_is_telephone($oldPhone) || !lt_is_telephone($newPhone)){
            $this->jsonReturn(0,'电话格式不正确');
        }
        if($oldPhone==$newPhone){
            $this->jsonReturn(0,'电话相同，无需更换');
        }
        $checkPhone=M('User')->where(['phone'=>$newPhone])->field('id')->find();
        if($checkPhone){
            $this->jsonReturn(0,'电话已存在');
        }
        $this->checkPhoneCode($oldPhone,$oldPhoneSms);
        $this->checkPhoneCode($newPhone,$newPhoneSms);
        $result=M('User')->where(['id'=>$this->userId])->save(['phone'=>$newPhone]);
        if($result!==false){
            $this->jsonReturn(1,'修改成功');
        }else{
            $this->jsonReturn(0,'修改失败');
        }
    }

    /**
     * 获取全部消息
     */
    public function getMessages(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $messages=M('Message')->where(['user_id'=>$this->userId])->order('create_time DESC')->limit($start,$this->pageLimit+1)->field('id,title,is_read')->select();
        if($messages){
            $messages=$this->checkEndPage($messages);
            $this->jsonReturn(1,'获取成功',$messages);
        }else{
            $this->jsonReturn(1,'还没有任何消息',(object)[]);
        }
    }

    /**
     * 删除消息
     */
    public function deleteMessage(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $message=M('Message')->where(['user_id'=>$this->userId,'id'=>$id])->field('id')->find();
        if(!$message){
            $this->jsonReturn(0,'消息不存在');
        }
        $result=M('Message')->where(['id'=>$id])->delete();
        if($result){
            $this->jsonReturn(1,'删除成功');
        }else{
            $this->jsonReturn(0,'删除失败');
        }
    }

    /**
     * 用户收藏店铺
     */
    public function collectBusiness(){
        $business_id=I('id',0,'intval');
        if(!$business_id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($business_id);
        if($business){
            $collected=M('BusinessCollection')->where(['user_id'=>$this->userId,'business_id'=>$business_id])->find();
            if(!$collected){
                $result=M('BusinessCollection')->add(['user_id'=>$this->userId,'business_id'=>$business_id,'create_time'=>time()]);
                if($result!==false){
                    M('Business')->where(['id'=>$business_id])->setInc('collect_num');
                    $this->jsonReturn(1,'收藏成功');
                }else{
                    $this->jsonReturn(0,'收藏失败');
                }
            }else{
                $this->jsonReturn(0,'您已经已经收藏了该店铺');
            }
        }else{
            $this->jsonReturn(0,'商户不存在或已被禁用');
        }
    }

    /**
     * 用户取消收藏店铺
     */
    public function deleteCollectBusiness(){
        $business_id=I('id',0,'intval');
        if(!$business_id){
            $this->jsonReturn(0,'缺少参数');
        }
        $business=lt_get_simple_business_by_id($business_id);
        if($business){
            $collected=M('BusinessCollection')->where(['user_id'=>$this->userId,'business_id'=>$business_id])->find();
            if($collected){
                $result=M('BusinessCollection')->where(['id'=>$collected['id']])->delete();
                if($result!==false){
                    M('Business')->where(['id'=>$business_id])->setDec('collect_num');
                    $this->jsonReturn(1,'取消收藏成功');
                }else{
                    $this->jsonReturn(0,'取消收藏失败');
                }
            }else{
                $this->jsonReturn(0,'您并没收藏改店铺');
            }
        }else{
            $this->jsonReturn(0,'商户不存在或已被禁用');
        }
    }

    //获取已收藏的店铺
    public function getCollectedBusinesses(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $collections=M('BusinessCollection')
            ->alias('bc')
            ->join('LEFT JOIN __BUSINESS__ as b ON b.id=bc.business_id')
            ->where(['bc.user_id'=>$this->userId,'b.status'=>1,'b.is_checked'=>1])
            ->order('bc.create_time DESC')
            ->limit($start,$this->pageLimit+1)
            ->field('b.id,b.logo,b.name')
            ->select();
        if($collections){
            foreach ($collections as &$collection){
                $collection['logo']=empty($collection['logo'])?'':$this->uploadPre.$collection['logo'];
            }
            $collections=$this->checkEndPage($collections);
            $this->jsonUnslashesReturn(1,'获取成功',$collections);
        }else{
            $this->jsonReturn(1,'还没有任何收藏',(object)[]);
        }
    }

    //订单提交
    public function submit(){
        $id=I('id',0,'intval');
        $price=I('price',0,'intval');
        $type=I('type',0,'intval');
        $lat=I('lat');
        $lng=I('lng');
        if(!$lat||!$lng||!$id){
            $this->jsonReturn(0,'请开启定位');
        }
        if($price<=0){
            $this->jsonReturn(0,'价格不正确');
        }
        //检测服务和商户状态
        $service=M('BusinessService')->where(['id'=>$id,'is_deleted'=>0])->find();
        if(!$service){
            $this->jsonReturn(0,'服务不存在');
        }
        $business=M('Business')->where(['id'=>$id,'status'=>1,'is_checked'=>1,'is_prepared'=>1])->field('id')->find();
       // $business=lt_get_simple_business_by_id($service['business_id']);
        if(!$business){
            $this->jsonReturn(0,'此商户还不能下单');
        }
        $time=time();
        if($type!=3){
            $data['payment']=1;
            $data['status']=0;
        }else{
            //线下支付直接已付款
            $data['payment']=3;
            $data['status']=1;
            $data['paid_time']=$time;
            //插入价格往来表
            $result=M('PriceLog')->add(['user_id'=>$this->userId,'receive_user_id'=>$business['id'],'price'=>$price,'create_time'=>$time,'type'=>1,'category'=>3]);
            if($result===false){
                $this->jsonReturn(0,'下单失败');
            }
            lt_check_and_push($business['id']);
        }
        $sn=sp_get_order_sn();
        $data['lat']=$lat;
        $data['lng']=$lng;
        $data['total']=$price;
        $data['create_time']=$time;
        $data['sn']=$sn;
        $data['user_id']=$this->userId;
        $data['price']=$service['price'];
        $data['name']='一号点评'.'-'.$service['name'];
        $data['business_service_id']=$service['id'];
        $data['business_service_name']=$service['name'];
        //开启事物
        M('Order')->startTrans();
        try {
            //插入订单表
            $result=M('Order')->add($data);
            if($result===false){
                throw new Exception('订单生成失败！');
            }
            //增加订单数
            $result = M('BusinessService')->where(['id' => $service['id']])->save(['order_number' => ['exp','`order_number`+1'],'true_order_number' => ['exp','`true_order_number`+1']]);
            if ($result === false) {
                throw new Exception('增加订单数失败！');
            }
            M('Order')->commit();
            $this->jsonReturn(1,'下单成功',['sn'=>$sn,'price'=>$price]);
        } catch (Exception $e) {
            M('Order')->rollback();
            $this->jsonReturn(0,$e->getMessage());
        }
    }

    //改变支付方式
    private function changePayType($type,$id){
        $result=M('Order')->where(['id'=>$id])->save(['payment'=>$type]);
        return $result;
    }

    //检测订单所属商户和服务状态
    private function checkBusinessByOrder($id){
        $service=M('BusinessService')->where(['id'=>$id])->field('is_deleted,business_id')->find();
        if(!$service){
            $this->jsonReturn(0,'该服务异常');
        }
        if($service['is_deleted']==1){
            $this->jsonReturn(0,'该服务异常');
        }
        $business=M('Business')->where(['id'=>$service['business_id']])->field('status,is_checked')->find();
        if(!$business){
            $this->jsonReturn(0,'商户异常');
        }
        if($business['status']!=1||$business['is_checked']!=1){
            $this->jsonReturn(0,'商户异常');
        }
    }

    //检测活动订单所属商户和活动状态
    private function checkBusinessByActivityOrder($id){
        $activity=M('BusinessActivity')->where(['id'=>$id])->field('is_deleted,business_id,end_time')->find();
        if(!$activity){
            $this->jsonReturn(0,'该活动异常');
        }
        if($activity['is_deleted']==1){
            $this->jsonReturn(0,'该活动异常');
        }
        if($activity['end_time']<time()){
            $this->jsonReturn(0,'该活动已结束');
        }
        $business=M('Business')->where(['id'=>$activity['business_id']])->field('status,is_checked')->find();
        if(!$business){
            $this->jsonReturn(0,'商户异常');
        }
        if($business['status']!=1||$business['is_checked']!=1){
            $this->jsonReturn(0,'商户异常');
        }
    }

    //微信预订单,1
    public function getBeforeOrderByWx(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_unpaid_order_by_sn($sn,$this->userId);
        if(!$order){
            $this->jsonReturn(0,'订单不存在');
        }
        $this->checkBusinessByOrder($order['business_service_id']);
        $result=$this->changePayType(1,$order['id']);
        if($result!==false){
           // $beforeOrder=(new WxpayService())->appPay($order['sn'], $order['name'], 0.01);
            $beforeOrder=(new WxpayService())->appPay($order['sn'], $order['name'], $order['total']);
            if($beforeOrder){
                $this->jsonReturn(1,'请求成功',$beforeOrder);
            }else{
                $this->jsonReturn(0,'请求失败');
            }
        }else{
            $this->jsonReturn(0,'更改失败');
        }
    }

    //支付宝预订单,2
    public function getBeforeOrderByAlipay(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_unpaid_order_by_sn($sn,$this->userId);
        if(!$order){
            $this->jsonReturn(0,'订单不存在');
        }
        $this->checkBusinessByOrder($order['business_service_id']);
        $result=$this->changePayType(2,$order['id']);
        if($result!==false){
            $beforeOrder=D('Common/Alipay','Service')->appPay($order['sn'], "订单编号{$order['sn']}", $order['total']);
            if($beforeOrder){
                $this->jsonReturn(1,'请求成功',$beforeOrder);
            }else{
                $this->jsonReturn(0,'请求失败');
            }
           // $this->jsonReturn(1,'请求成功');
        }else{
            $this->jsonReturn(0,'更改失败');
        }
    }

    //获取用户订单
    public function getOrders(){
        //99为全部订单
        $status=I('status',99,'intval');
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        if($status!=99){
            $where['o.status']=$status;
        }
        $where['user_id']=$this->userId;
        $where['user_is_deleted']=0;
        $orders=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->join('LEFT JOIN __BUSINESS__ as b ON b.id=bs.business_id')
            ->where($where)
            ->order('o.create_time DESC')
            ->limit($start,$this->pageLimit+1)
            ->field('o.sn,o.business_service_name,o.total,b.logo,b.name,b.lat,b.long as lng,o.status,o.is_complained')
            ->select();
        if($orders){
            foreach ($orders as &$order){
                $order['logo']=empty($order['logo'])?'':$this->uploadPre.$order['logo'];
            }
            $orders=$this->checkEndPage($orders);
            $this->jsonUnslashesReturn(1,'获取成功',$orders);
        }else{
            $this->jsonReturn(1,'还没有订单',(object)[]);
        }
    }

    //获取用户订单
    public function deleteOrder(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_order_by_sn($sn,$this->userId);
        if($order){
            //只有未支付和已完成可以隐藏
            if($order['status']!=0&&$order['status']!=3){
                $this->jsonReturn(0,'只有未支付和已完成订单可以删除');
            }
            $result=M('Order')->where(['id'=>$order['id']])->save(['user_is_deleted'=>1]);
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //投诉
    public function complain(){
        $sn=I('sn');
        $content=I('content');
        $images=I('images');
        if(!$content){
            $this->jsonReturn(0,'内容必填');
        }
        if(!$sn||!$content||!$images||!is_array($images)){
            $this->jsonReturn(0,'图片必填');
        }
        foreach ($images as &$image){
            $image=$this->getSaveImageUrl($image);
        }
        $order=lt_get_order_by_sn($sn,$this->userId);
        if($order){
            if($order['status']!=3){
                $this->jsonReturn(0,'已评价的订单才可以投诉');
            }
            if($order['is_complained']==1){
                $this->jsonReturn(0,'该订单已投诉');
            }
            $result=M('Order')->where(['id'=>$order['id']])->save(['is_complained'=>1,'complain'=>$content,'complain_images'=>json_encode($images,JSON_UNESCAPED_SLASHES)]);
            if($result!==false){
                $this->jsonReturn(1,'投诉成功');
            }else{
                $this->jsonReturn(0,'投诉失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //订单评价
    public function orderComment(){
        $sn=I('sn');
        $star=I('star',0,'intval');
        $content=I('content','');
        if(!$sn||!$star||$star>5||$star<1){
            $this->jsonReturn(0,'星级不正确');
        }
        $order=lt_get_order_by_sn($sn,$this->userId);
        if($order){
            if($order['status']!=2){
                $this->jsonReturn(0,'已消费订单才能评价');
            }
            $comment=M('BusinessServiceComment')->where(['order_id'=>$order['id']])->field('id')->find();
            if($comment){
                $this->jsonReturn(0,'订单已评价');
            }
            //计算得分
            $service=M('BusinessService')->where(['id'=>$order['business_service_id']])->field('id,business_id')->find();
            if($service){
                $business_id=$service['business_id'];
                $business=M('Business')->where(['id'=>$business_id])->field('points')->find();
                if($business){
                    //如果商户以前没有评价则此评价为商户初始评分
                    if($business['points']=='0.0'){
                        M('Business')->where(['id'=>$business_id])->save(['points'=>$star]);
                    }else{
                        $services=M('BusinessService')->where(['business_id'=>$business_id])->select();
                        $service_ids=array_column($services,'id');
                        $count=M('BusinessServiceComment')->where(['business_service_id'=>['in',$service_ids]])->field('id')->count();
                        $count=intval($count)+1;
                        $sum=M('BusinessServiceComment')->where(['business_service_id'=>['in',$service_ids]])->sum('star');
                        $sum=$sum+$star;
                        //最低0.1分
                        $points=sprintf("%.1f",($sum/$count));
                        if($points=='0.0'){
                            $points='0.1';
                        }
                        M('Business')->where(['id'=>$business_id])->save(['points'=>$points]);
                    }
                }
            }
            //开启事务
            M('BusinessServiceComment')->startTrans();
            try {
                //插入评论表
                $data['star']=$star;
                $data['content']=$content;
                $data['user_id']=$this->userId;
                $data['create_time']=time();
                $data['username']=$this->user['username'];
                $data['avatar']=$this->user['avatar'];
                $data['order_id']=$order['id'];
                $data['business_service_id']=$order['business_service_id'];
                $result=M('BusinessServiceComment')->add($data);
                if ($result === false) {
                    throw new Exception('评论失败！');
                }
                //更改用户状态
                $result = M('Order')->where(['id' => $order['id']])->save(['status' => 3]);
                if ($result === false) {
                    throw new Exception('更改用户状态失败！');
                }
                M('BusinessServiceComment')->commit();
                $this->jsonReturn(1,'评价成功');
            } catch (Exception $e) {
                M('BusinessServiceComment')->rollback();
                $this->jsonReturn(0,$e->getMessage());
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //收支明细
    public function getPriceLogDetails(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        //用户端只有用户给商户钱
        $logs=M('PriceLog')
            ->alias('p')
            ->join("LEFT JOIN __BUSINESS__ as b ON b.id=p.receive_user_id")
            ->where(['p.user_id'=>$this->userId,'p.type'=>1])
            ->order('p.create_time DESC')
            ->limit($start,$this->pageLimit+1)
            ->field('p.id,b.name,p.create_time,p.price,p.category')
            ->select();
        if($logs){
            foreach ($logs as &$log){
                $log['price']=sprintf('%.2f',-$log['price']);
            }
            $logs=$this->checkEndPage($logs);
            $this->jsonReturn(1,'获取成功',$logs);
        }else{
            $this->jsonReturn(1,'获取成功',(object)[]);
        }
    }

    //获取起止日期每天的数组
    public function getDays($start,$end){
        $start=strtotime(date("Y-m-d",$start));
        $end=strtotime(date("Y-m-d",$end));
        $differ=$end-$start;
        if($differ<0){
            return false;
        }
        $one_day=60*60*24;
        $day=$differ/$one_day;
        $d=[];
        for ($i=0;$i<=$day;$i++){
            $d[]=$start+$i*$one_day;
        }
        return $d;
    }

    //曲线数据
    public function getCurve(){
        $start=I('start',0,'intval');
        $end=I('end',0,'intval');
        if(!$start||!$end){
            $this->jsonReturn(0,'时间必须');
        }
        $days=$this->getDays($start,$end);
        if(!$days){
            $this->jsonReturn(0,'参数错误');
        }
        //用户端金钱记录
        $logs=M('PriceLog')
            ->where(['user_id'=>$this->userId,'type'=>1,'create_time'=>['between',[$start,$end]]])
            ->field('create_time,price,category')
            ->select();
        if($logs){
            $result=[];
            //按每天分组
            foreach ($days as $day){
                foreach ($logs as $log){
                    if($day==strtotime(date("Y-m-d",$log['create_time']))){
                        $result[$day][]=$log;
                    }
                }
            }
            foreach ($result as $kk=>&$value){
                $total=0;
                $online=0;
                $outline=0;
                $sao=0;
                foreach ($value as $k=>$v){
                    switch ($v['category']){
                        case 1 : $online+=$v['price'];break;
                        case 2 : $sao+=$v['price'];break;
                        case 3 : $outline+=$v['price'];break;
                    }
                    $total+=$v['price'];
                    unset($value[$k]);
                }
                $value['total']=sprintf("%.2f",$total);
                $value['online']=sprintf("%.2f",$online);
                $value['outline']=sprintf("%.2f",$outline);
                $value['sao']=sprintf("%.2f",$sao);
                $value['time']="$kk";
            }
            //补全数组,1线上，2扫码，3线下，4记账
            $keys=array_keys($result);
            $array_diff=array_diff($days,$keys);
            if($array_diff){
                foreach ($array_diff as $item){
                    $result[$item]=['total'=>'0.00','online'=>'0.00','outline'=>'0.00','sao'=>'0.00','time'=>"$item"];
                }
            }
            ksort($result);
            $result=array_values($result);
            $this->jsonReturn(1,'获取成功',$result);
        }else{
            $this->jsonReturn(1,'没有支出',[]);
        }
    }

    //活动订单提交
    public function ActivitySubmit(){
        $id=I('id',0,'intval');
        $lat=I('lat');
        $lng=I('lng');
        if(!$lat||!$lng||!$id){
            $this->jsonReturn(0,'请开启定位');
        }
        $businessActivity=M('BusinessActivity')->where(['id'=>$id,'is_deleted'=>0])->find();
        if($businessActivity){
            $business=lt_get_normal_business_by_id($businessActivity['business_id']);
            if(!$business){
                $this->jsonReturn(0,'商户已被禁用');
            }
            if($business['is_prepared']!=1){
                $this->jsonReturn(0,'此商户还不能下单');
            }
            $activityUsed=M('OrderActivity')->where(['user_id'=>$this->userId,'business_activity_id'=>$id])->field('id')->find();
            if($activityUsed){
                $this->jsonReturn(0,'已领取活动');
            }
            //判断是否是最近的活动
            $businessActivityNearly=lt_get_nearly_simple_activity_by_business($business['id']);
            if(!$businessActivityNearly){
                $this->jsonReturn(0,'活动已结束');
            }
            if($businessActivityNearly['id']!=$id){
                $this->jsonReturn(0,'活动已结束');
            }
            $time=time();
            if($businessActivity['start_time']>$time){
                $this->jsonReturn(0,'活动还未开始');
            }
            $sn=sp_get_order_sn();
            $data['lat']=$lat;
            $data['lng']=$lng;
            $data['total']=$businessActivity['price'];
            $data['create_time']=$time;
            $data['sn']=$sn;
            $data['user_id']=$this->userId;
            $data['name']='一号点评'.'-'.$businessActivity['name'];
            $data['business_activity_id']=$businessActivity['id'];
            //开启事物
            M('OrderActivity')->startTrans();
            try {
                //加锁
                $businessActivity=M('BusinessActivity')->where(['id'=>$id])->lock(true)->find();
                //库存不足
                $inventory=intval($businessActivity['inventory']);
                if($inventory<=0){
                    $this->jsonReturn(0,'活动已结束');
                }
                //插入订单表
                $result=M('OrderActivity')->add($data);
                if($result===false){
                    throw new Exception('订单生成失败！');
                }
                //增加订单数
                $result = M('BusinessActivity')->where(['id' => $businessActivity['id']])->save(['order_number' => ['exp','`order_number`+1'],'inventory' => ['exp','`inventory`-1']]);
                if ($result === false) {
                    throw new Exception('增加订单数失败！');
                }
                M('OrderActivity')->commit();
                $this->jsonReturn(1,'下单成功',['sn'=>$sn,'price'=>$businessActivity['price']]);
            } catch (Exception $e) {
                M('OrderActivity')->rollback();
                $this->jsonReturn(0,$e->getMessage());
            }
        }else{
            $this->jsonReturn(0,'活动已结束');
        }
    }

    //获取活动订单
    public function getActivityOrders(){
        //99为全部订单
        $status=I('status',99,'intval');
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        if($status!=99){
            $where['o.status']=$status;
        }
        $where['user_id']=$this->userId;
        $where['user_is_deleted']=0;
        $orders=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as ba ON ba.id=o.business_activity_id')
            ->join('LEFT JOIN __BUSINESS__ as b ON b.id=ba.business_id')
            ->where($where)
            ->order('o.create_time DESC')
            ->limit($start,$this->pageLimit+1)
            ->field('o.sn,ba.name as business_activity_name,o.total,b.logo,b.name,b.lat,b.long as lng,o.status,o.is_complained')
            ->select();
        if($orders){
            foreach ($orders as &$order){
                $order['logo']=empty($order['logo'])?'':$this->uploadPre.$order['logo'];
            }
            $orders=$this->checkEndPage($orders);
            $this->jsonUnslashesReturn(1,'获取成功',$orders);
        }else{
            $this->jsonReturn(1,'还没有订单',(object)[]);
        }
    }

    //获取用户订单
    public function deleteActivityOrder(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_activity_order_by_sn($sn,$this->userId);
        if($order){
            //只有未支付和已完成可以隐藏
            if($order['status']!=0&&$order['status']!=2){
                $this->jsonReturn(0,'只有未支付和已完成订单可以删除');
            }
            $result=M('OrderActivity')->where(['id'=>$order['id']])->save(['user_is_deleted'=>1]);
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //投诉活动
    public function complainActivity(){
        $sn=I('sn');
        $content=I('content');
        $images=I('images');
        if(!$content){
            $this->jsonReturn(0,'内容必填');
        }
        if(!$sn||!$images||!is_array($images)){
            $this->jsonReturn(0,'图片必填');
        }
        foreach ($images as &$image){
            $image=$this->getSaveImageUrl($image);
        }
        $order=lt_get_activity_order_by_sn($sn,$this->userId);
        if($order){
            if($order['status']!=2){
                $this->jsonReturn(0,'已完成的订单才可以投诉');
            }
            if($order['is_complained']==1){
                $this->jsonReturn(0,'该订单已投诉');
            }
            $result=M('OrderActivity')->where(['id'=>$order['id']])->save(['is_complained'=>1,'complain'=>$content,'complain_images'=>json_encode($images,JSON_UNESCAPED_SLASHES)]);
            if($result!==false){
                $this->jsonReturn(1,'投诉成功');
            }else{
                $this->jsonReturn(0,'投诉失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //活动支付微信预订单,1
    public function getBeforeActivityOrderByWx(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_unpaid_activity_order_by_sn($sn,$this->userId);
        if(!$order){
            $this->jsonReturn(0,'订单不存在');
        }
        $this->checkBusinessByActivityOrder($order['business_activity_id']);
        //存储支付类型
        $result=M('OrderActivity')->where(['id'=>$order['id']])->save(['payment'=>1]);
        if($result!==false){
            // $beforeOrder=(new WxpayService())->appPay($order['sn'], $order['name'], 0.01,2);
            $beforeOrder=(new WxpayService())->appPay($order['sn'], $order['name'], $order['total'],2);
            if($beforeOrder){
                $this->jsonReturn(1,'请求成功',$beforeOrder);
            }else{
                $this->jsonReturn(0,'请求失败');
            }
        }else{
            $this->jsonReturn(0,'更改失败');
        }
    }

    //活动线下支付
    public function getBeforeActivityOrderByOutline(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_unpaid_activity_order_by_sn($sn,$this->userId);
        if(!$order){
            $this->jsonReturn(0,'订单不存在');
        }
        $this->checkBusinessByActivityOrder($order['business_activity_id']);
        $activity=M('BusinessActivity')->where(['id'=>$order['business_activity_id']])->find();
        lt_check_and_push($activity['business_id']);
        //线下支付直接已付款
        $data['payment']=3;
        $data['status']=1;
        $data['paid_time']=time();
        //开启事物
        M('OrderActivity')->startTrans();
        try {
            //插入信息表
            $result=M('OrderActivity')->where(['id'=>$order['id']])->save($data);
            if ($result === false) {
                throw new Exception('下单失败！');
            }
            //插入价格往来表
            $result=M('PriceLog')->add(['user_id'=>$this->userId,'receive_user_id'=>$activity['business_id'],'price'=>$order['total'],'create_time'=>time(),'type'=>1,'category'=>3]);
            if ($result === false) {
                throw new Exception('下单失败！');
            }
            M('OrderActivity')->commit();
            $this->jsonReturn(1,'支付成功');
        } catch (Exception $e) {
            M('OrderActivity')->rollback();
            $this->jsonReturn(0,$e->getMessage());
        }
    }

    //活动支付支付宝预订单,2
    public function getBeforeActivityOrderByAlipay(){
        $sn=I('sn');
        if(!$sn){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=lt_get_unpaid_activity_order_by_sn($sn,$this->userId);
        if(!$order){
            $this->jsonReturn(0,'订单不存在');
        }
        $this->checkBusinessByActivityOrder($order['business_activity_id']);
        //存储支付类型
        $result=M('OrderActivity')->where(['id'=>$order['id']])->save(['payment'=>2]);
        if($result!==false){
            // $beforeOrder=(new WxpayService())->appPay($order['sn'], $order['name'], 0.01,2);
            $beforeOrder=D('Common/Alipay','Service')->appPay($order['sn'], $order['name'], $order['total'],2);
            if($beforeOrder){
                $this->jsonReturn(1,'请求成功',$beforeOrder);
            }else{
                $this->jsonReturn(0,'请求失败');
            }
        }else{
            $this->jsonReturn(0,'更改失败');
        }
    }

    //获取是否有未读消息
    public function getUnreadMessage(){
        $message=M('Message')->where(['user_id'=>$this->userId,'is_read'=>0])->field('id')->find();
        if($message){
            $this->jsonReturn(1,'请求成功','1');
        }else{
            $this->jsonReturn(1,'请求成功','0');
        }
    }
}